define(function(require, exports, module){
	// var base = "http://localhost:8888/bookmark/web/index.php/";
	var base = "http://bookmark.zeroplace.cn/index.php/";
	// var base = "http://localhost:8080/web/index.php/";

	var Error = require("base").Error;
	// var base = require("base");
	var TokenError = require("base").TokenError;

	return {
		setBase: function(newBase){
			base = newBase;
		},
		getBase: function(){
			return base;
		},
		call: function(apiname, params, callback){
			// alert(JSON.stringify(apiname));
			console.log(apiname, params);

			var ret = null;
			var error = null;

			var loginManager = require("login-manager");
			var accessToken = loginManager.getAccessToken() ;
			if (accessToken) {
				$.ajax({
					"url" : base + apiname,
					"method" : "post",
					"data" : params,
					"headers" : {
						"Access-Token" : accessToken
					}
				}).done(function(json){
					/**
					 * 调用正常，有正确的JSON数据返回
					 */
					callback(json, error);
				}).fail(function(req){
					/**
					 * 无正常数据返回
					 */
					if (req.status == 401) {
						/**
						 * 令牌可能失效了
						 */
						callback(null, new TokenError("Unauthorized"));
					} else {
						callback(null, new require("base").ApiError("unknow error, status: " + req.status));
					}
				});	
			} else {
				/**
				 * 本地没有存储令牌
				 */
				error = "cant't get access token";
				callback(ret, new TokenError(error));
			}
		},
		bareCall: function(apiname, params, callback){
			$.ajax({
				"url" : base + apiname,
				"method" : "post",
				"data" : params
			}).done(function(json){
				callback(json, null);
			}).fail(function(req){
				callback(null, new require("base").ApiError('unknow error, status: ' + req.status));
			});
		},
		callEx: function(apiname, params){
			return this.withDef("call", apiname, params);
		},
		bareCallEx: function(apiname, params){
			return this.withDef("bareCall", apiname, params);
		},
		withDef: function(call, apiname, params){
			var dtd = $.Deferred();

			this[call].call(this, apiname, params, function(json, error){
				if (error) {
					dtd.reject(error);
				} else {
					dtd.resolve(json);
				}
			});

			return dtd.promise();
		}
	};
});